from PySide6.QtWidgets import (QDialog, QVBoxLayout, QLabel, QPushButton,
                               QGridLayout, QWidget, QFrame)
from PySide6.QtCore import Qt


class StatisticsDialog(QDialog):
    def __init__(self, audio_canvas, parent=None):
        super().__init__(parent)
        self.audio_canvas = audio_canvas
        self.theme = "dark"  # 默认主题
        self.initUI()

    # 在 initUI 方法中修改网格布局部分
    def initUI(self):
        self.setWindowTitle("统计信息")
        self.setModal(True)
        self.resize(450, 350)  # 稍微调整大小以容纳更好的布局

        layout = QVBoxLayout()
        layout.setSpacing(15)
        layout.setContentsMargins(20, 20, 20, 20)

        # 收集统计信息
        nodes = self.audio_canvas.getAllNodes()
        connections = self.audio_canvas.getAllConnections()

        # 按类型统计节点
        node_type_count = {}
        for node in nodes:
            if hasattr(node, 'nodeType'):
                node_type = node.nodeType
                node_type_count[node_type] = node_type_count.get(node_type, 0) + 1

        # 创建网格布局显示统计信息
        grid_widget = QWidget()
        grid_widget.setObjectName("statsGrid")  # 设置对象名用于样式表
        self.grid_layout = QGridLayout()
        self.grid_layout.setSpacing(8)
        self.grid_layout.setContentsMargins(15, 15, 15, 15)

        # 基本统计 - 使用更清晰的布局
        title_label = QLabel("系统统计信息")
        title_label.setStyleSheet("font-weight: bold; font-size: 12pt; padding-bottom: 10px;")
        self.grid_layout.addWidget(title_label, 0, 0, 1, 2, Qt.AlignCenter)

        # 添加分隔线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setFrameShadow(QFrame.Sunken)
        self.grid_layout.addWidget(separator, 1, 0, 1, 2)

        self.grid_layout.addWidget(QLabel("总节点数:"), 2, 0)
        total_nodes_label = QLabel(str(len(nodes)))
        total_nodes_label.setProperty("important", "true")
        self.grid_layout.addWidget(total_nodes_label, 2, 1)

        self.grid_layout.addWidget(QLabel("总连接数:"), 3, 0)
        total_conn_label = QLabel(str(len(connections)))
        total_conn_label.setProperty("important", "true")
        self.grid_layout.addWidget(total_conn_label, 3, 1)

        # 节点类型统计
        if node_type_count:
            type_title = QLabel("节点类型分布:")
            type_title.setStyleSheet("font-weight: bold; margin-top: 10px;")
            self.grid_layout.addWidget(type_title, 4, 0, 1, 2)

            row = 5
            for node_type, count in node_type_count.items():
                try:
                    subsystem = self.audio_canvas.apsParser.getSubSystem(node_type)
                    node_name = subsystem.get('name', node_type) if subsystem else node_type
                except:
                    node_name = node_type

                self.grid_layout.addWidget(QLabel(f"  {node_name}:"), row, 0)
                count_label = QLabel(str(count))
                self.grid_layout.addWidget(count_label, row, 1)
                row += 1

        grid_widget.setLayout(self.grid_layout)

        # 添加关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(self.close)
        close_button.setFixedWidth(120)

        layout.addWidget(grid_widget)
        layout.addWidget(close_button, 0, Qt.AlignCenter)

        self.setLayout(layout)

        # 应用主题
        self.applyTheme(self.theme)

    def setTheme(self, theme):
        """设置对话框主题"""
        self.theme = theme
        self.applyTheme(theme)

    def applyTheme(self, theme):
        """应用主题样式 - 优化版本"""
        if theme == "light":
            self.setStyleSheet("""
                QDialog {
                    background-color: #f0f0f0;
                    color: #000000;
                    font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
                }
                QLabel {
                    color: #000000;
                    background-color: transparent;
                    font-size: 9pt;
                    padding: 2px;
                }
                QLabel[important="true"] {
                    font-weight: bold;
                    font-size: 10pt;
                    color: #000080;
                }
                QPushButton {
                    background-color: #e0e0e0;
                    color: #000000;
                    border: 1px solid #c0c0c0;
                    border-radius: 3px;
                    padding: 8px 20px;
                    font-weight: bold;
                    font-size: 9pt;
                    min-width: 80px;
                }
                QPushButton:hover {
                    background-color: #d0d0d0;
                    border: 1px solid #a0a0a0;
                }
                QPushButton:pressed {
                    background-color: #c0c0c0;
                }
                QPushButton:focus {
                    outline: 1px solid #8080ff;
                }
                /* 网格布局容器样式 */
                QWidget#statsGrid {
                    background-color: #f8f8f8;
                    border: 1px solid #d0d0d0;
                    border-radius: 5px;
                    padding: 10px;
                }
            """)

            # 为重要标签设置属性
            for i in range(self.grid_layout.count()):
                item = self.grid_layout.itemAt(i)
                if item and item.widget() and isinstance(item.widget(), QLabel):
                    label = item.widget()
                    # 如果是标题或重要信息，标记为重要
                    if i == 0 or "总节点数" in label.text() or "总连接数" in label.text():
                        label.setProperty("important", "true")

        else:  # dark theme
            self.setStyleSheet("""
                QDialog {
                    background-color: #2b2b2b;
                    color: #ffffff;
                    font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
                }
                QLabel {
                    color: #ffffff;
                    background-color: transparent;
                    font-size: 9pt;
                    padding: 2px;
                }
                QLabel[important="true"] {
                    font-weight: bold;
                    font-size: 10pt;
                    color: #6496ff;
                }
                QPushButton {
                    background-color: #404040;
                    color: #ffffff;
                    border: 1px solid #555555;
                    border-radius: 3px;
                    padding: 8px 20px;
                    font-weight: bold;
                    font-size: 9pt;
                    min-width: 80px;
                }
                QPushButton:hover {
                    background-color: #505050;
                    border: 1px solid #777777;
                }
                QPushButton:pressed {
                    background-color: #606060;
                }
                QPushButton:focus {
                    outline: 1px solid #7777ff;
                }
                /* 网格布局容器样式 */
                QWidget#statsGrid {
                    background-color: #353535;
                    border: 1px solid #454545;
                    border-radius: 5px;
                    padding: 10px;
                }
            """)

            # 为重要标签设置属性
            for i in range(self.grid_layout.count()):
                item = self.grid_layout.itemAt(i)
                if item and item.widget() and isinstance(item.widget(), QLabel):
                    label = item.widget()
                    # 如果是标题或重要信息，标记为重要
                    if i == 0 or "总节点数" in label.text() or "总连接数" in label.text():
                        label.setProperty("important", "true")

